// pages/my/orderList.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "我的订单", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: ''
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    orderTypeList: [{
      id: 1,
      name: "预约订单"
    }, {
      id: 2,
      name: "商城订单"
    }],
    curOrderTypeId: 1, //订单类型
    tabList: [{
      id: 0,
      name: '全部'
    }, {
      id: 1,
      name: '待使用'
    }, {
      id: 2,
      name: '已完成'
    }, {
      id: 3,
      name: '退款中'
    }, {
      id: 4,
      name: '已过期'
    }],
    tabId: 0, //其他订单状态下标
    shoppingTabList: [{
      id: 100,
      name: '全部'
    }, {
      id: 0,
      name: '待支付'
    }, {
      id: 1,
      name: '待发货'
    }, {
      id: 2,
      name: '已发货'
    }, {
      id: 3,
      name: '退款中'
    }, {
      id: 4,
      name: '已完成'
    }],
    shoppingTabId: 100, //商城功能状态下标
    orderList: [],
    orderDsyList: [],
    orderYsyList: [],
    orderYgqList: [],
    orderTkzList: [],
    orderTotalList: [],

    shopOrderTotalList: [],
    shopOrderDzfList: [],
    shopOrderDfhList: [],
    shopOrderYfhList: [],
    shopOrderTkzList: [],
    shopOrderYwcList: [],

    openid: '',
    shareTitle: '',
    shareImg: '',
    isOne: 0,
    shopOrderList: [],
    getOtherData: 0,
    getShopData: 0,
    shopOrderStatusArr: [],
    targetTimestamp: new Date().getTime() + 7 * 24 * 60 * 60 * 1000,
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,
    djsTotalArr: [],
    djsDzfArr: []
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  changeOrderType(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    that.setData({
      curOrderTypeId: id
    });
    if (id == 1 && that.data.getOtherData == 0) {
      //还未请求过其他订单数据
      that.getOrderListPageInfo(that.data.openid);
    } else if (id == 2 && that.data.getShopData == 0) {
      //还未请求过商城订单数据
      that.getShopOrderListPageInfo(that.data.openid);
    }
  },
  tab(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let orderList = [];
    if (id == 0) {
      //全部
      orderList = that.data.orderTotalList;
    } else if (id == 1) {
      //待使用
      orderList = that.data.orderDsyList;
    } else if (id == 2) {
      //已使用
      orderList = that.data.orderYsyList;
    } else if (id == 3) {
      //退款中
      orderList = that.data.orderTkzList;
    } else {
      //已过期
      orderList = that.data.orderYgqList;
    }
    that.setData({
      tabId: id,
      orderList: orderList
    });
  },
  shoppingTab(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    that.setData({
      shoppingTabId: id,
    });

    let shopOrderList = [];
    if (id == 100) {
      //全部
      shopOrderList = that.data.shopOrderTotalList;
    } else if (id == 0) {
      //待支付
      shopOrderList = that.data.shopOrderDzfList;
    } else if (id == 1) {
      //待发货
      shopOrderList = that.data.shopOrderDfhList;
    } else if (id == 2) {
      //已发货
      shopOrderList = that.data.shopOrderYfhList;
    } else if (id == 3) {
      //退款中
      shopOrderList = that.data.shopOrderTkzList;
    } else if (id == 4) {
      //已完成
      shopOrderList = that.data.shopOrderYwcList;
    }
    that.setData({
      shopOrderList: shopOrderList
    });
  },

  //点击立即支付
  pay(e) {
    var that = this;
    var pid = e.currentTarget.dataset.id;
    var bmType = e.currentTarget.dataset.type;
    if (bmType == 'activity') {
      //活动
      wx.navigateTo({
        url: '/pages/activityCenter/bmSure?pid=' + pid
      });
    } else if (bmType == 'space') {
      //空间预约
      wx.navigateTo({
        url: '/pages/orderCenter/siteOrder/spaceDetail/index?orderId=' + pid
      });
    } else if (bmType == 'mgy') {
      //蘑菇乐园
      wx.navigateTo({
        url: '/pages/orderCenter/mgyOrder/detail?id=' + pid
      });
    } else if (bmType == 'newbm') {
      //原滩公园
      wx.navigateTo({
        url: '/pages/orderCenter/newBmOrder/detail?id=' + pid
      });
    }else if (bmType == 'xl') {
      //寻麓之旅
      wx.navigateTo({
        url: '/pages/orderCenter/xlzlOrder/peer-payment/peer-payment?id=' + pid
      });
    }
  },

  //跳转满意度
  myd(e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/my/mydQuestion?id=' + id + "&type=" + type
    });
  },

  //申请退款
  retrunPay(e) {
    var id = e.currentTarget.dataset.id;
    var bmType = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/pages/activityCenter/refund?id=' + id + "&bmType=" + bmType
    });
  },
  //删除商城订单
  delShopOrder(e) {
    var that = this;
    var status = e.currentTarget.dataset.status;
    var id = e.currentTarget.dataset.id;
    var parentId = e.currentTarget.dataset.parentid;

    //提示用户是否确认取消订单
    wx.showModal({
      title: '温馨提示',
      content: '您确认删除此订单吗?',
      complete: (res) => {
        if (res.confirm) {
          //确认删除
          wx.showLoading({
            title: '订单删除中...',
            mask: true
          })
          wx.request({
            url: that.data.baseUrl + 'delShopOrder.php',
            method: 'POST',
            data: {
              'openid': that.data.openid,
              'id': id,
              'parentId': parentId,
              'orderStatus': status
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              wx.hideLoading();
              app.showTip(res.data.msg);
              if (res.data.status == 1) {
                //重新加载数据
                setTimeout(function () {
                  that.getShopOrderListPageInfo(that.data.openid);
                }, 1000);
              }
            },
            fail: function () {
              wx.hideLoading();
              app.showTip('抱歉,服务器繁忙');
            }
          });
        }
      }
    });
  },
  //商城申请退款
  shopRefund(e) {
    var that = this;
    var status = e.currentTarget.dataset.status;
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/shoppingMall/refund?orderId=' + id
    });
  },
  //撤销退款
  resetRefund(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    //提示用户是否确认撤销退款
    wx.showModal({
      title: '温馨提示',
      content: '请再次确认是否撤销退款',
      complete: (res) => {
        if (res.confirm) {
          //确认删除
          wx.showLoading({
            title: '撤销退款中...',
            mask: true
          })
          wx.request({
            url: that.data.baseUrl + 'cancelShopOrderRefund.php',
            method: 'POST',
            data: {
              'openid': that.data.openid,
              'orderId': id
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              wx.hideLoading();
              app.showTip(res.data.msg);
              if (res.data.status == 1) {
                //重新加载数据
                setTimeout(function () {
                  that.getShopOrderListPageInfo(that.data.openid);
                }, 1000);
              }
            },
            fail: function () {
              wx.hideLoading();
              app.showTip('抱歉,服务器繁忙');
            }
          });
        }
      }
    });
  },
  //确认收货
  enterSh(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    //提示用户是否确认收货
    wx.showModal({
      title: '温馨提示',
      content: '请再次确认是否收到商品',
      complete: (res) => {
        if (res.confirm) {
          //确认删除
          wx.showLoading({
            title: '确认收货中...',
            mask: true
          })
          wx.request({
            url: that.data.baseUrl + 'enterShopOrder.php',
            method: 'POST',
            data: {
              'openid': that.data.openid,
              'orderId': id
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              wx.hideLoading();
              app.showTip(res.data.msg);
              if (res.data.status == 1) {
                //重新加载数据
                setTimeout(function () {
                  that.getShopOrderListPageInfo(that.data.openid);
                }, 1000);
              }
            },
            fail: function () {
              wx.hideLoading();
              app.showTip('抱歉,服务器繁忙');
            }
          });
        }
      }
    });
  },
  //商品评价
  evaluate(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/shoppingMall/evaluate?smallOrderId=' + id + "&isEdit=0"
    })
  },
  //查看评价
  lookEvaluate(e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/shoppingMall/selfEvaluate?smallOrderId=' + id
    })
  },
  //重新购买
  copyShopping(e) {
    var that = this;
    var status = e.currentTarget.dataset.status;
    var id = e.currentTarget.dataset.id;
    var parentId = e.currentTarget.dataset.parentid;
    //提示用户是否重新购买
    wx.showModal({
      title: '温馨提示',
      content: '请再次确认是否重新购买此订单中的商品',
      complete: (res) => {
        if (res.confirm) {
          //确认删除
          wx.showLoading({
            title: '商品购买中...',
            mask: true
          })
          wx.request({
            url: that.data.baseUrl + 'copyShoppingOrder.php',
            method: 'POST',
            data: {
              'openid': that.data.openid,
              'parentId': parentId
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              wx.hideLoading();
              if (res.data.status == 1) {
                //重新加载数据
                wx.navigateTo({
                  url: '/pages/shoppingMall/order?orderId=' + res.data.orderId + "&shop_id=" + res.data.shop_id
                });
              } else {
                app.showTip(res.data.msg);
              }
            },
            fail: function () {
              wx.hideLoading();
              app.showTip('抱歉,服务器繁忙');
            }
          });
        }
      }
    });

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;


    var headerFlag = options.headerFlag;
    var id = options.id;
    var orderType = options.orderType;
    //orderType = 'shop';
    if (headerFlag == 'cj') {
      that.setData({
        ['defaultData.goUrl']: '/pages/index/index'
      });
    } else if (headerFlag == 'ms') {
      that.setData({
        ['defaultData.goUrl']: '/pages/index/index'
      });
    } else if (headerFlag == 'kd') {
      that.setData({
        ['defaultData.goUrl']: '/pages/index/index'
      });
    } else if (headerFlag == 'space') {
      that.setData({
        ['defaultData.goUrl']: '/pages/index/index'
      });
    } else {
      that.setData({
        ['defaultData.goUrl']: '/pages/my/index'
      });
    }

    if (orderType == 'shop') {
      that.setData({
        curOrderTypeId: 2
      });
    }


    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                if (orderType == 'shop') {
                  //请求商城
                  that.getShopOrderListPageInfo(res.data.openid);
                } else {
                  //请求其他订单
                  that.getOrderListPageInfo(res.data.openid);
                }
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      if (orderType == 'shop') {
        //请求商城
        that.getShopOrderListPageInfo(openid);
      } else {
        //请求其他订单
        that.getOrderListPageInfo(openid);
      }
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本业数据--其他订单
  getOrderListPageInfo(openid) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getOrderListPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          that.setData({
            orderTotalList: res.data.orderTotalList,
            orderDsyList: res.data.orderDsyList,
            orderYsyList: res.data.orderYsyList,
            orderYgqList: res.data.orderYgqList,
            orderTkzList: res.data.orderTkzList,
            getOtherData: 1
          });

          var orderList = [];
          if (that.data.tabId == 0) {
            //全部
            orderList = res.data.orderTotalList;
          } else if (that.data.tabId == 1) {
            //待使用
            orderList = res.data.orderDsyList;
          } else if (that.data.tabId == 2) {
            //已完成
            orderList = res.data.orderYsyList;
          } else if (that.data.tabId == 3) {
            //退款中
            orderList = res.data.orderTkzList;
          } else if (that.data.tabId == 4) {
            //已过期
            orderList = res.data.orderYgqList;
          }
          that.setData({
            orderList: orderList
          });
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },

  //获取本页数据---商城
  getShopOrderListPageInfo(openid) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getShopOrderListPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //重新赋值后台请求数据 shoppingTabId
          that.setData({
            shopOrderTotalList: res.data.shopOrderTotalList,
            shopOrderDzfList: res.data.shopOrderDzfList,
            shopOrderDfhList: res.data.shopOrderDfhList,
            shopOrderYfhList: res.data.shopOrderYfhList,
            shopOrderTkzList: res.data.shopOrderTkzList,
            shopOrderYwcList: res.data.shopOrderYwcList,
            shopOrderStatusArr: res.data.shopOrderStatusArr,
            getShopData: 1,
            djsTotalArr: res.data.djsTotalArr,
            djsDzfArr: res.data.djsDzfArr
          });

          //赋值当前数据
          var shopOrderList = [];
          if (that.data.shoppingTabId == 100) {
            //全部
            shopOrderList = res.data.shopOrderTotalList;
          } else if (that.data.shoppingTabId == 0) {
            //待支付
            shopOrderList = res.data.shopOrderDzfList;
          } else if (that.data.shoppingTabId == 1) {
            //待发货
            shopOrderList = res.data.shopOrderDfhList;
          } else if (that.data.shoppingTabId == 2) {
            //已发货
            shopOrderList = res.data.shopOrderYfhList;
          } else if (that.data.shoppingTabId == 3) {
            //退款中
            shopOrderList = res.data.shopOrderTkzList;
          } else if (that.data.shoppingTabId == 4) {
            //已完成
            shopOrderList = res.data.shopOrderYwcList;
          }

          if ((that.data.shoppingTabId == 100 || that.data.shoppingTabId == 0) && res.data.djsDzfArr.length > 0) {
            //全部 or 待支付
            that.updateCountdown();
            // 每隔一秒更新一次
            that.timer = setInterval(() => {
              that.updateCountdown();
              console.log(111)
            }, 1000);
          }

          that.setData({
            shopOrderList: shopOrderList
          });
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },

  //支付倒计时
  updateCountdown: function () {
    var that = this;
    const now = Date.now();

    var arr = []
    if (that.data.shoppingTabId == 100) {
      //全部订单
      arr = that.data.djsTotalArr;
    } else {
      //待支付订单
      arr = that.data.djsDzfArr;
    }
    var shopOrderList = that.data.shopOrderList;
    for (let i = 0; i < arr.length; i++) {
      let distance = parseInt(arr[i].payEndSjc) * 1000 - now;
      if (distance <= 0) {
        return
      }
      // 计算剩余时间
      let days = Math.floor(distance / (1000 * 60 * 60 * 24));
      let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      let seconds = Math.floor((distance % (1000 * 60)) / 1000);
      days = days < 10 ? '0' + days : days,
        hours = hours < 10 ? '0' + hours : hours,
        minutes = minutes < 10 ? '0' + minutes : minutes,
        seconds = seconds < 10 ? '0' + seconds : seconds

      //if (!(days == 0 && hours == 0 && minutes == 0 && seconds == 0)) {
      if (!(minutes == 0 && seconds == 0)) {
        if (shopOrderList.length > 0) {
          shopOrderList[arr[i].row].minAndSec = minutes + ":" + seconds;
          that.setData({
            shopOrderList
          });
        }
      } else {
        if (shopOrderList.length > 0) {
          shopOrderList[arr[i].row].minAndSec = "00:00";
          that.setData({
            shopOrderList
          });
        }
      }
    }
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  //跳转至订单详情页
  goDetail(e) {
    var that = this;
    var flag = e.currentTarget.dataset.flag;
    var id = e.currentTarget.dataset.id;
    var status = e.currentTarget.dataset.status;
    if(flag==='xl'){
      wx.navigateTo({
        url: '/pages/orderCenter/xlzlOrder/order-details?id=' + id +"&type="+ flag+ '&orderStatus=' + status
      });
    }else  if (flag == 'cj' || flag == 'ms') {
      //抽奖或秒杀
      wx.navigateTo({
        url: '/pages/lotteryDrawPage/LotteryOrderDetail/index?id=' + id + "&type=" + flag
      });
    } else if (flag == 'kd') {
      //快递预约
      wx.navigateTo({
        url: '/pages/expressReservation/detail/index?id=' + id
      });
    } else if (flag == 'space') {
      //空间预约
      wx.navigateTo({
        url: '/pages/orderCenter/siteOrder/spaceDetail/detail?id=' + id
      });
    } else {
      //其他预约
      wx.navigateTo({
        url: '/pages/my/orderDetail?id=' + id + "&type=" + flag + '&orderStatus=' + status
      });
    }

  },
  // 跳转到商城订单详情
  goShoppingDetail(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var parentId = e.currentTarget.dataset.parentid;
    var status = e.currentTarget.dataset.status;

    wx.navigateTo({
      url: '/pages/shoppingMall/orderDetail?orderId=' + id + "&parentId=" + parentId
    });
  },
  //前往支付
  goPay(e) {
    var orderId = e.currentTarget.dataset.id;
    var shop_id = e.currentTarget.dataset.shopid;
    wx.navigateTo({
      url: '/pages/shoppingMall/order?orderId=' + orderId + "&shop_id=" + shop_id
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    if (that.data.isOne == 0) {
      that.setData({
        isOne: 1
      });
    } else {
      //刷新页面数据
      if (that.data.curOrderTypeId == 1) {
        that.getOrderListPageInfo(that.data.openid);
      } else {
        that.getShopOrderListPageInfo(that.data.openid, that.data.shoppingTabId);
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.clearTimer();
  },
  clearTimer() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.clearTimer();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})